/*************************************************************************
> File Name: queue.c
> Author: icebear
> Mail: 3322366195@qq.com
> Created Time: 2023-07-24 21:45:05
> Description: 不使用size暂存长度数组实现循环队列
************************************************************************/
#include "queue.h"
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
int main(int argc, char const *argv[])
{
    Queue *queue;
    printf("create:\n");
    queue = create();
    printf("size:%3d\n", size(queue));
    printf("isEmpty:%3d\n", isEmpty(queue));
    printf("push: 0-9\n");
    for (int i = 0; i < 10; i++)
    {
        push(queue, i);
    }
    printf("size:%3d\n", size(queue));
    printf("isEmpty:%3d\n", isEmpty(queue));
    printf("pop: 5 item\n");
    for (int i = 0; i < 5; i++)
    {
        printf("%3d", pop(queue));
    }
    printf("\n");
    printf("size:%3d\n", size(queue));
    printf("clear:\n");
    clear(queue);
    printf("isEmpty:%3d\n", isEmpty(queue));
    printf("size:%3d\n", size(queue));
    return 0;
}

Queue *create()
{
    Queue *queue = malloc(sizeof(Queue));
    queue->front = 0;
    queue->tail = 0;
    return queue;
}
void destory(Queue *queue)
{
    free(queue);
}
void push(Queue *queue, int item)
{
    if ((queue->tail + 1) % MAXSIZE == queue->front)
    {
        printf("Queue is full,nable to push.\n");
        return;
    }
    queue->data[queue->tail] = item;
    queue->tail = (queue->tail + 1) % MAXSIZE;
}
int pop(Queue *queue)
{
    if (isEmpty(queue))
    {
        printf("Queue is empty,nable to pop.\n");
        return 0;
    }
    int item = queue->data[queue->front];
    queue->front = (queue->front + 1) % MAXSIZE;
    return item;
}
int peek(Queue *queue)
{
    if (isEmpty(queue))
    {
        printf("Queue is empty,nable to peek.\n");
        return 0;
    }
    return queue->data[queue->front];
}
void clear(Queue *queue)
{
    queue->tail = queue->front = 0;
}
int isEmpty(Queue *queue)
{
    return queue->front == queue->tail;
}
int size(Queue *queue)
{
    return (queue->tail - queue->front + MAXSIZE) % MAXSIZE;
}
int is_full(Queue *queue)
{
    return (queue->tail + 1) % MAXSIZE == queue->front;
}